package leeon.bbsbrower.views;

import ipworks.IPWorksException;
import leeon.bbsbrower.actions.BBSBlockAction;
import leeon.bbsbrower.models.BlockObject;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;

public class BlockView extends ViewPart {
	public static final String ID = "bbsbrower.view.block";

	//列表
	private List list = null;
	//数据
	private static BlockObject[] blocks = null;

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	public void createPartControl(Composite parent) {
		
		new Label(parent, SWT.NONE);
		
		//讨论块列表
		list = new List(parent, SWT.NONE);
		list.setFont(ApplicationWorkbenchWindowAdvisor.defaultFont);
		
		//上下左右的事件
		list.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				//左
				if (e.keyCode == SWT.ARROW_LEFT) {
					actionToMain();
					e.doit = false;
				//右
				} else if (e.keyCode == SWT.ARROW_RIGHT || e.keyCode == 13) {										
					actionBoardList();					
					e.doit = false;
				}
			}

			public void keyReleased(KeyEvent e) {}
			
		});
		
		new Label(parent, SWT.NONE);
	}
	
	
	/**
	 * 回主选单
	 */
	private void actionToMain() {		
		//跳转到主界面
		IWorkbenchPage page = this.getViewSite().getPage();
		page.hideView(this);
		try {
			page.showView(MainView.ID);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 进入某个讨论区
	 */
	private void actionBoardList() {
		//根据讨论区查询版面的action
		int block = list.getSelectionIndex();
		String url = blocks[block].getURL();
		
		//跳转到某个讨论区的版面列表界面
		IWorkbenchPage page = this.getViewSite().getPage();
		page.hideView(this);
		try {						
			BoardListView board = (BoardListView)page.showView(BoardListView.ID);
			board.refreshData(block, url, 0, 1);
			
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 刷新数据
	 * @param blocks
	 */
	public void refreshData(int index) {
		//获取所有block的数据
		try {
			blocks = BBSBlockAction.getBlocks();
		} catch (IPWorksException e) {
			MessageDialog.openError(this.getViewSite().getShell(), "错误信息", e.toString());
			e.printStackTrace();
		}
				
		list.removeAll();
		if (blocks != null) {
			for (int i = 0; i < blocks.length; i ++) {
				list.add(blocks[i].getName());
			}
			//登陆进来时选中0
			list.select(index);
		}
		

		ApplicationActionBarAdvisor.setStatusLine();
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		list.setFocus();
	}
}